package cn.iocoder.yudao.module.member.controller.admin.student;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.SortingField;
import cn.iocoder.yudao.framework.common.util.io.FileUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.controller.admin.student.vo.*;
import cn.iocoder.yudao.module.member.controller.admin.studentEducationalExperience.vo.StudentEducationalExperienceRespVO;
import cn.iocoder.yudao.module.member.convert.student.StudentConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.student.StudentDO;
import cn.iocoder.yudao.module.member.dal.dataobject.studentCurriculumVitae.StudentFileDO;
import cn.iocoder.yudao.module.member.service.student.StudentService;
import cn.iocoder.yudao.module.member.service.studentCurriculumVitae.StudentCurriculumVitaeService;
import cn.iocoder.yudao.module.member.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 -运营端- 学生管理")
@RestController
@RequestMapping("/member/student")
@Validated
@Slf4j
public class StudentController {

    @Resource
    private StudentService studentService;
    @Resource
    private StudentCurriculumVitaeService studentCurriculumVitaeService;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Value("${yudao.excel.path}")
    private String excelPath;

    @PostMapping("/create")
    @ApiOperation("创建学生管理")
    public CommonResult<Long> createStudent(@Valid @RequestBody StudentCreateReqVO createReqVO) {
        return success(studentService.createStudent(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新学生管理")
    public CommonResult<Boolean> updateStudent(@Valid @RequestBody StudentUpdateReqVO updateReqVO) {
        studentService.updateStudent(updateReqVO);
        return success(true);
    }

    @PutMapping("/examine")
    @ApiOperation("审核学生管理")
    public CommonResult<Boolean> examine(@Valid @RequestBody StudentUpdateReqVO updateReqVO) {
        studentService.examine(SecurityFrameworkUtils.getLoginUserId().toString(),updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除学生管理")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    public CommonResult<Boolean> deleteStudent(@RequestParam("id") Long id) {
        studentService.deleteStudent(id);

        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得学生管理")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<StudentRespVO> getStudent(@RequestParam("id") Long id) {
        StudentDO student = studentService.getStudent(id);
        return success(StudentConvert.INSTANCE.convert(student));
    }

    @GetMapping("/list")
    @ApiOperation("获得学生管理列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    public CommonResult<List<StudentRespVO>> getStudentList(@RequestParam("ids") Collection<Long> ids) {
        List<StudentDO> list = studentService.getStudentList(ids);
        return success(StudentConvert.INSTANCE.convertList(list));
    }

    @PostMapping("/page")
    @ApiOperation("获得学生管理分页")
    public CommonResult<PageResult<StudentRespVO>> getStudentPage(@Valid @RequestBody StudentPageReqVO pageVO) {
        PageResult<StudentDO> pageResult = studentService.getStudentPage(pageVO);
        return success(StudentConvert.INSTANCE.convertPage(pageResult));
    }

    @PostMapping("/getStudentInfoPage")
    @ApiOperation("运营-人才夹-学生列表")
    public CommonResult<PageResult<StudentInfoRespVO>> getStudentInfoPage(@Valid @RequestBody StudentPageReqVO pageVO) {
        if(  null==pageVO.getSortField()){
            SortingField sf=new SortingField();
            sf.setField("update_time");
            sf.setOrder("desc");
            pageVO.setSortField(sf);
        }
        pageVO.setRelationType(2);
        PageResult<StudentInfoRespVO> pageResult = studentService.getStudentInfoPage(pageVO);
        return success(pageResult);
    }


    @PostMapping("/getStudentEducationalExperienceByStudentId")
    @ApiOperation("运营-人才夹-根据学生ID查看教育经历")
    public CommonResult<List<StudentEducationalExperienceRespVO>> getStudentEducationalExperienceByStudentId(@NotNull(message = "学生ID不能为空") Long studentId) {
        List<StudentEducationalExperienceRespVO> list = studentService.getStudentEducationalExperienceByStudentId(studentId);
        return success(list);
    }

    @PostMapping("/getPushStudentInfoPage")
    @ApiOperation("运营-推送-学生列表选择")
    public CommonResult<PageResult<StudentInfoRespVO>> getPushStudentInfoPage( @RequestBody StudentInfoPageReqVO pageVO) {
        if(  null==pageVO.getSortField()){
            SortingField sf=new SortingField();
            sf.setField("update_time");
            sf.setOrder("desc");
            pageVO.setSortField(sf);
        }
        PageResult<StudentInfoRespVO> pageResult = studentService.getPushStudentInfoPage(pageVO);
        return success(pageResult);
    }

//    @GetMapping("/export-excel")
//    @ApiOperation("导出学生管理 Excel")
//    @OperateLog(type = EXPORT)
//    public void exportStudentExcel(@Valid StudentExportReqVO exportReqVO,
//              HttpServletResponse response) throws IOException {
//        List<StudentDO> list = studentService.getStudentList(exportReqVO);
//        // 导出 Excel
//        List<StudentExcelVO> datas = StudentConvert.INSTANCE.convertList02(list);
//        ExcelUtils.write(response, "学生信息.xls", "数据", StudentExcelVO.class, datas);
//    }
    @GetMapping("/regist/count")
    @ApiOperation("时间段学生注册数量")
    public CommonResult<Integer> getStudentRegistCount( String startDate,  String endDate) {
        return success(studentService.getStudentRegistCount(startDate,endDate));
    }



    @PostMapping("/export-excel")
    @ApiOperation("导出学生信息简历信息 Excel")
    @OperateLog(type = EXPORT)
    public void exportStudentInfo(@RequestBody StudentPageReqVO pageVO,
                                   HttpServletResponse response) {
            PageResult<StudentDO> pageResult = studentService.getStudentPage(pageVO);
        List<StudentDO> list=pageResult.getList();
        List<StudentExcel> datas = studentCurriculumVitaeService.exportStudent(list);
        ExcelUtil.exportExcel(datas,excelPath,1,response);
    }


    @PostMapping("/exportAllStudent")
    @ApiOperation("导出所有学生信息")
    @OperateLog(type = EXPORT)
    public CommonResult<Boolean> exportAllStudent(@RequestBody StudentPageReqVO pageVO,
                                  HttpServletResponse response) {
        PageResult<StudentDO> pageResult = studentService.getStudentPage(pageVO);
        List<StudentDO> list=pageResult.getList();
        // 导出 Excel
        threadPoolTaskExecutor.execute(()->{
            Date date=new Date();
            List<StudentExcel> datas = studentCurriculumVitaeService.exportStudent(list);
            String path = ExcelUtil.exportExcel(datas, excelPath, 2, response);
            if(StringUtils.isNotBlank(path)){
                StudentFileDO s=new  StudentFileDO();
                s.setFilePath(path);
                s.setFileName(path.substring(path.lastIndexOf("/")+1,path.length()) );
                s.setCreator(SecurityFrameworkUtils.getLoginUser().getUsername() );
                s.setCreateTime(date);
                studentCurriculumVitaeService.saveStudentFile(s);
            }
        });
        return success(true);
    }






    @PostMapping("/getStudentInfoDownPath")
    @ApiOperation("获取学生信息下载链接 Excel")
    public CommonResult< PageResult<StudentFileVO> > getStudentInfoDownPath(@RequestBody   StudentPageReqVO pageReqVO)   {
        PageResult<StudentFileVO>  pageResult = studentCurriculumVitaeService.getStudentFileList(pageReqVO);
        return success(pageResult);
    }

    /**
     * 通用下载请求
     *
     * @param filePath 文件名称
     */
    @GetMapping("/download")
    @ApiOperation("下载请求")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "filePath",value ="文件名称",dataType ="string",required = true),
    })
    public void fileDownload(@ApiIgnore @NotBlank(message = "路径不能为空") String filePath,
                             HttpServletResponse response, HttpServletRequest request)
            throws  Exception{
        String fileName=filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
        if (!FileUtils.isValidFilename(fileName)) {
            ErrorCode errorCode=new ErrorCode(300,"文件名称非法，不允许下载。 ");
            throw exception(errorCode);
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
        FileUtils.writeBytes(filePath, response.getOutputStream());
    }


    @PostMapping("/import-excel")
    @ApiOperation("导入学生Excel")
    @ApiImplicitParam(name = "file", value = "Excel 文件", required = true, dataTypeClass = MultipartFile.class)
    public CommonResult<String> studentImportExcel(@RequestParam("file") MultipartFile file ) throws IOException {
        // 导入 Excel
        List<StudentExcelImportVO> list=ExcelUtils.read(file,StudentExcelImportVO.class);
        String msg = studentService.studentImportExcel(list);
        return success(msg);
    }

    @PostMapping("/saveStudent")
    @ApiOperation("录入学生")
    public CommonResult<Boolean> saveStudent(@Valid @RequestBody StudentExcelImportVO student )  {
        // 导入 Excel
        List<StudentExcelImportVO> list=new ArrayList<>();
        list.add(student);
        studentService.studentImportExcel(list);
        return success(true);
    }
}
